#!/usr/bin/python
# coding=utf8
###############################################################################
#													 		  
#	Copyright 2007 Danil Dotsenko, Pavel Nemec					
#																
#	This program is free software; you can redistribute it and/or modify	 
#	it under the terms of the GNU Lesser General Public License as published 
#	by the Free Software Foundation; either version 2 of the License, or	 
#	(at your option) any later version.									  
#																			
#	This program is distributed in the hope that it will be useful,		  
#	but WITHOUT ANY WARRANTY; without even the implied warranty of		   
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the			
#	GNU Lesser General Public License for more details.					  
#																			 
#	You should have received a copy of the GNU Lesser General Public License 
#	along with this program; if not, write to the Free Software			  
#	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA 
#																			 
###############################################################################								   #
# author:
# Danil Dotsenko  dd@accentsolution.com						   #
# Pavel Nemec	  nemecp4@gmail.com

# todo: finish conversion to class (pavel)



 
import karamba
import os
import readvcard
from commands import getoutput
maxAppletHeight=240

class Config:
	'''
	class Config serve for obtain user-default settings
	'''
	maxAppletHeight=240
	def __init__(self,widget):
		self.theme=karamba.readConfigEntry(widget,"theme")
		if self.theme==None :
			self.theme="aqua"
		print "theme is: ",self.theme
		self.textAreaPositionX=20
		#images are 32x32
		#start x=textAreaPositionX
		#start y=textAreaPositionY
		# KISS !!
		self.w=widget
		self.images=[] #karamba references to image
		self.texts=[] #karamba references to text
		#files
		y=10
		yesX=120
		noX=140
		#Header
		self.headertext=karamba.createText(self.w,self.textAreaPositionX,y+10,120,15,"Configuration menu")
		karamba.changeTextSize(self.w,self.headertext,13)
		self.texts.append(self.headertext)
		#icon
		self.help=karamba.createImage(self.w,self.textAreaPositionX+yesX,y,self.getImage("help.png"))
		karamba.attachClickArea(self.w,self.help)
		self.images.append(self.help)
		y+=60
		
		
		#open file
		self.open=karamba.createImage(self.w,self.textAreaPositionX,y,self.getImage("kuser_small.png"))
		self.images.append(self.open)
		#text
		self.filetext=karamba.createText(self.w,self.textAreaPositionX+30,y,100,15,"Add vCal file")
		self.texts.append(self.filetext)
		
		#yes
		self.fileOpen=karamba.createImage(self.w,self.textAreaPositionX+yesX,y,self.getImage("fileopen.png"))
		karamba.attachClickArea(self.w,self.fileOpen)
		karamba.addImageTooltip(self.w,self.fileOpen,"Open new vCal files.")
		self.images.append(self.fileOpen)
		#no
		self.fileDelete=karamba.createImage(self.w,self.textAreaPositionX+noX,y,self.getImage("close.png"))
		karamba.attachClickArea(self.w,self.fileDelete)
		karamba.addImageTooltip(self.w,self.fileDelete,"Delete all stored vCal files.")
		self.images.append(self.fileDelete)
		y+=35
		
		#kmail
		self.mail_enable=karamba. readConfigEntry(self.w,"mail")
		self.kmail=karamba.createImage(self.w,self.textAreaPositionX,y-5,self.getImage("kmail.png"))	
		self.images.append(self.kmail)
		#
		#text
		self.mailtext=karamba.createText(self.w,self.textAreaPositionX+30,y,100,15,"Enable Kmail")
		self.texts.append(self.mailtext)
		
		#yes
		if self.mail_enable==None or len(self.mail_enable)==0 or self.mail_enable=="yes":
			self.kmailYes=karamba.createImage(self.w,self.textAreaPositionX+yesX,y,self.getImage("ok.png"))
		else: 
			self.kmailYes=karamba.createImage(self.w,self.textAreaPositionX+yesX,y,self.getImage("ok_grey.png"))
		karamba.attachClickArea(self.w,self.kmailYes)
		self.images.append(self.kmailYes)
		y+=35
		
		#kopete
		self.im_enable=karamba.readConfigEntry(self.w,"im")
		print "im_enable: %s " % self.im_enable
		self.kopete=karamba.createImage(self.w,self.textAreaPositionX,y-5,self.getImage("kopete.png"))
		self.images.append(self.kopete)
		#
		#text
		self.kopeteText=karamba.createText(self.w,self.textAreaPositionX+30,y,100,15,"Enable Kopete")
		self.texts.append(self.kopeteText)
		
		#yes
		self.kopeteYes=karamba.createImage(self.w,self.textAreaPositionX+yesX,y,self.getImage("ok.png"))
		karamba.attachClickArea(self.w,self.kopeteYes)
		self.images.append(self.kopeteYes)
		y+=35
		
		
		
		#Theming
		self.umicon=karamba.createImage(self.w,self.textAreaPositionX+10,self.maxAppletHeight-30,"images/umicon_unselected.png")
		self.aqua=karamba.createImage(self.w,self.textAreaPositionX+60,self.maxAppletHeight-30,"images/aqua_selected.png")
		self.crystal=karamba.createImage(self.w,self.textAreaPositionX+100,self.maxAppletHeight-30,"images/crystal_unselected.png")
		self.changeThemePicture(self.theme)
		
		karamba.attachClickArea(self.w,self.aqua)
		karamba.attachClickArea(self.w,self.crystal)
		karamba.attachClickArea(self.w,self.umicon)
		self.images.append(self.aqua)
		self.images.append(self.crystal)
		self.images.append(self.umicon)
		self.hide()
	def __ini2dict__(self, text):
		'''
		Very basic ini-style text parser. Only treats '=' as key, value separators.
		Takes either a list type of separate lines, or one string/unicode type
		which it splits and strips.
		Returns a dict object with converted contents of the text.
		'''

		if not type(text)==type([]):
			text = [ i.strip() for i in text.splitlines() if i] # throwing away empty lines, removing extra spaces.
		root = {}
		active = root # if no sections are found, all key, value pairs are assigned to root.
		for i in text:
			if i[0]=='[' and i[len(i)-1]==']':
				# new section name, make it active
				i = i.strip('[]')
				root[i]={}
				active = root[i]
			else:
				# key, value pair, obatin it and add to active list
				try:
					key, value = i.split('=',1)
					active[key]=value
				except:
#					wrong values? do not add them to list
					pass
		return root
	
	def __getUserFiles(self):
		'''
		This will help you identify all vCard files user selected 
		(connected) in Kaddressbook  (KDE)
		We return a list of full local paths to each file. Duplicate files are removed!
		'''
		try:
			cfgdirs = getoutput('kde-config --path config').split(':')
		except:
			cfgdirs = ''
		resources = {}
		#print "Config.getUserFiles: found ",len(cfgdirs), " configuration paths to serach in."
		for path in cfgdirs:
			# found user's address book settings file.
			try:
				resources = self.__ini2dict__(open(path+'kresources/contact/stdrc').read())
				# this is now a dict object with the contents of the rc file.
#				break
			except:
#				no serious error, resource probably contains no kaddresbook configuration
				pass
		filenames = {}

		if resources:
			# now, resourcesDict is a list of sections with Resource_ in the name.

			resourcesDict = [resources[i] for i in resources if i.count('Resource_')] 
			for i in resourcesDict:
				try:
					vcard = bool(i['FileFormat']=='vcard')
					active = bool(i['ResourceIsActive']=='true')
				except:
					print "exception in going trough keys", i
					vcard = False
					active = False
				if vcard and active: # there are 2.5 types of vCard entries in the kde contacts file
					if i.has_key('FileName'): # the single vCard file
						file = i['FileName'].replace('$HOME', os.environ['HOME'])
						#if not allready here add file to list
						if file not in filenames:
							filenames[file]=1
					elif i.has_key('FilePath'): # the vCard folder (folder with vCard files)
						path = i['FilePath'].replace('$HOME', os.environ['HOME']) + '/'
						try:
							filenames.extend([path+j for j in os.listdir(path)])
						except:
							pass
					else: # this is the "half" part. if no path is specified, use kde default 
						file = os.environ['HOME']+'/.kde/share/apps/kabc/std.vcf'
						#if not allready here add file  list
						if file not in filenames:
							filenames[file]=1
							
			return filenames.keys()
	
	def storeVCardReader(self, reader):	
		self.reader=reader
		for i in self.__getUserFiles():	
			self.reader.addFile(i)
	
	def getImage(self,imageName):
		''' Return path to right image in right theme'''
		return "images/"+self.theme+"/"+imageName
	def hide(self):
		for i in self.images:
			karamba.hideImage(self.w,i)
		for i in self.texts:
			karamba.hideText(self.w,i)
	def show(self):
		for i in self.images:
			karamba.showImage(self.w,i)
		for i in self.texts:
			karamba.showText(self.w,i)
	def mouseEvent(self,component):
		#print "self.configurator have an event"
		c=component
		#who have event?
		if c==self.help:
			cin,cout = os.popen2("konqueror help/index.html")
			lines = cout.read()
			cin.close()
			cout.close()
		elif c==self.fileOpen:
			#print "open file"
			cin,cout = os.popen2("kfiledialog --files")
			lines = cout.read()
			cin.close()
			cout.close()
			files= lines.split()
			for i in files:
				file=i.replace("\n","")
				self.reader.addFile(i)
				print "parsing file: ",file
		elif c==self.fileDelete:
			karamba.writeConfigEntry(self.w,"files","")
#			self.reader.deleteAllFiles()
			print "deleteFile"
		elif c==self.kmailYes:
			if self.mail_enable=="no":
				self.mail_enable="yes"
				karamba.setImagePath(self.w,self.kmailYes,self.getImage("ok.png"))
				karamba.writeConfigEntry(self.w,"mail",self.mail_enable)
			else:
				self.mail_enable="no"
				karamba.setImagePath(self.w,self.kmailYes,self.getImage("ok_grey.png"))
				karamba.writeConfigEntry(self.w,"mail",self.mail_enable) 
			print "kmail is %s" % self.mail_enable
		elif c==self.kopeteYes:
			if self.im_enable=="no":
				self.im_enable="yes"
				karamba.setImagePath(self.w,self.kopeteYes,self.getImage("ok.png"))
				karamba.writeConfigEntry(self.w,"im",self.im_enable)
			else:
				self.im_enable="no"
				karamba.setImagePath(self.w,self.kopeteYes,self.getImage("ok_grey.png"))
				karamba.writeConfigEntry(self.w,"im",self.im_enable) 
			print "im is %s" % self.mail_enable
		elif c==self.aqua:
			karamba.writeConfigEntry(self.w,"theme","aqua")
			self.changeThemePicture("aqua")
		elif c==self.crystal:
			karamba.writeConfigEntry(self.w,"theme","crystal")
			self.changeThemePicture("crystal")
		elif c==self.umicon:
			karamba.writeConfigEntry(self.w,"theme","umicon")
			self.changeThemePicture("umicon")
		else:
			print "unknown"

	def changeThemePicture(self,theme):
		self.theme=theme
		print "change theme called with ", theme
		if theme == "aqua":
			karamba.setImagePath(self.w,self.aqua,		"images/aqua_selected.png")
			karamba.setImagePath(self.w,self.crystal,	"images/crystal_unselected.png")
			karamba.setImagePath(self.w,self.umicon,	"images/umicon_unselected.png")
			print "aqua selected"
		elif theme == "crystal":			
			karamba.setImagePath(self.w,self.aqua,		"images/aqua_unselected.png")
			karamba.setImagePath(self.w,self.crystal,	"images/crystal_selected.png")
			karamba.setImagePath(self.w,self.umicon,	"images/umicon_unselected.png")
			print "crystal selected"
		elif theme == "umicon":
			karamba.setImagePath(self.w,self.aqua,		"images/aqua_unselected.png")
			karamba.setImagePath(self.w,self.crystal,	"images/crystal_unselected.png")
			karamba.setImagePath(self.w,self.umicon,	"images/umicon_selected.png")
			print "umicon selected"
		else:
			print "unknown"
		
def test():
	''' test method for class Config'''
	c = Config()
	
	print "The following vCard files are found:"
	mylist = c.getUserFiles()
	if mylist == None:
		print "no user vCard files found grr"
	else:
		print "i get ",len(mylist), " files to print"
		for i in mylist:
			print i
			
#test()